const tool = require('./tool.js');
exports.main = main;
//全局参数对象
var params = {

}
//最短可以参与的福袋时间
minTime = 17
//最大参与福袋的时间
maxTime = 900
//不在直播间的最大次数，超过则重启抖音
var maxNotLiveCount = 20;
//一轮最多选择的直播间
var maxLiveCount = 20;
//一轮最多参与福袋的次数
var maxCount = 10;
//多少分钟未打开福袋则重启
var restartTime = 10;
//上一次参与福袋的时间
var lastJoinTime = new Date()
//不在直播间的次数
var notLiveCount = 0
//采集出可参与的福袋
var fudaiList = []
//当前参与的福袋
var fudai = null;
//重复进入直播间的次数
var enterLiveCount = 0;
//从什么地方进入直播间
var enterLiveFrom = '搜索';   //搜索,主页
//跳出采集次数
var breakCount = 0;
function main (p) {
    params = p
    start()
}

function start () {
    tool.restartApp("抖音")
    sleep(2000)
    enterHome()
}

//进入首页
function enterHome () {
    tool.log("进入首页")
    let live = getRoomName(500)
    if (live === null) {
        if (enterLiveFrom === '搜索') {
            enterLiveBySearch()
        } else if (enterLiveFrom === '首页') {
            //进入抖音首页
            tool.enterDouYinIndex()
            enterLiveByIndex()
        }
    } else {
        tool.log("从首页进入直播间")
        //进入总榜直播间
        enterTotalLive()
    }
}


//通过搜索进入直播间
function enterLiveBySearch () {
    tool.log("从搜索进入直播间")
    let live = getRoomName(500)
    if (live !== null) {
        //进入总榜
        enterTotalLive()
    } else {
        //点击搜索，进入直播间
        // if (tool.clickDesc("搜索")) {
        if (press(1150, 200, 40)) {
            tool.log("搜索")
            sleep(2000)
            setText(params.searchWord + "直播间")
            sleep(4000)
            tool.log("进入第一个搜索项")
            press(254, 400, 10)//第一个搜索项
            sleep(4000)
            if (tool.clickTextByScreenCapture('直播')) {
                sleep(4000)
                press(254, 1000, 10)//进入直播间
                sleep(5000)
                enterLiveBySearch()
            } else {
                enterHome()
            }
        } else {
            tool.log("没有搜索")
            enterHome()
        }
    }
}

//通过首页进入直播间
function enterLiveByIndex () {
    let live = getRoomName(500)
    if (live === null) {
        if (tool.clickTextByScreenCapture('直播')) {
            tool.log("进入直播")
            sleep(3000)
            press(500, 600, 10)
            sleep(3000)
            //进入直播广场
            enterLiveSquare()
        } else {
            let s = tool.getText("推荐")
            if (s !== null) {
                tool.log(`推荐:${JSON.stringify(s)}`)
                let startX = s['bounds']['left'] - 500
                let startY = s['bounds']['top']
                let endX = s['bounds']['left']
                let endY = s['bounds']['top']
                tool.log("移动推荐")
                swipe(startX, startY, device.width - 20, endY, 300)
                sleep(500)
                enterLiveByIndex()
            } else {
                //返回首页
                enterHome()
            }
        }
    } else {
        //进入直播广场
        enterLiveSquare()
    }
}

//进入直播广场
function enterLiveSquare () {
    tool.log("进入直播广场")
    if (tool.clickText('更多直播')) {
        tool.log("进入直播广场")
        sleep(2000)
        //进入购物直播间
        enterShoppingLive()
    } else {
        //进入下一个直播间
        nextLive(5000)
        enterLiveSquare()
        sleep(3000)
    }
}

//进入卖货直播间
function enterShoppingLive () {
    if (tool.clickText('购物') || tool.clickDesc('卖货')) {
        tool.log("进入购物直播间")
        sleep(2000)
        press(500, 600, 10)
        sleep(3000)
        //进入总榜直播间
        enterTotalLive()
    } else {
        backLive(5000)
        // let s = tool.getText("推荐")
        // if (s !== null) {
        //     let startX = s['bounds']['left'] + 150
        //     let startY = s['bounds']['top'] + 10
        //     let endX = s['bounds']['left']
        //     let endY = s['bounds']['top']
        //     tool.log("移动推荐")
        //     swipe(startX, startY, endX, endY, 50)
        //     sleep(500)
        //     enterShoppingLive()
        // } else {
        //     enterHome()
        // }

    }
}

//进入总榜直播间
function enterTotalLive () {
    let live = getRoomName(500)
    if (live === null) {
        tool.log("重新搜索直播间")
        enterLiveBySearch()
        return
    }
    tool.log("查询总榜")
    if (tool.clickDesc('带货总榜')) {
        tool.log("进入带货总榜")
        sleep(2000)
        if (text("总榜").exists()) {
            tool.log("进入总榜")
            click(500, 1240)
            tool.log("进入总榜第一直播间")
            sleep(3000)
            let live = getRoomName(500)
            if (live !== null) {
                //采集福袋
                pickFudai()
            } else {
                enterTotalLive()
            }
        } else {
            tool.log("没有总榜")
            nextLive(5000)
            enterTotalLive()
        }
    } else {
        tool.log("没有带货总榜,切换下一个直播间")
        notLiveCount++
        if (notLiveCount > maxNotLiveCount) {
            notLiveCount = 0
            //通过搜索进入直播间
            enterLiveBySearch()
        }
        nextLive(5000)
        enterTotalLive()
    }
}

//采集可参与的福袋
function pickFudai () {
    if (breakCount >= 3) {
        start()
        return
    }
    tool.log("开始采集可参与的福袋")
    //重置采集的福袋数组
    fudaiList = []
    //查询福袋信息
    let fudai
    //是否遇到马上开奖的超级福袋
    let isSuper = false;
    let i = 1
    let fudaiName = null;
    for (i = 1; i < maxLiveCount; i++) {
        tool.log(`采集福袋:${i}`)
        //关闭悬浮窗
        tool.closeCoupon()
        //检查上一次参与福袋的时间
        checkRuning()
        let name = getRoomName(2000)
        if (fudaiName === name) {
            enterLiveCount++
            if (enterLiveCount >= 3) {
                enterLiveCount = 0
                tool.log(`和上一次直播间${name}一样${enterLiveCount},跳出采集`)
                breakCount++
                break
            } else {
                tool.log(`和上一次直播间${name}一样${enterLiveCount},继续采集`)
            }
        } else {
            enterLiveCount = 0
            if (i > 1) {
                breakCount = 0
            }
            // tool.log("和上一次直播间不一样，继续采集")
        }
        //获取福袋信息
        fudai = getFuBaoBaseInfo()
        fudaiName = fudai.name
        fudai.point = i
        //判断福袋是否值得参与
        let isJoinFuBao = hasJoinFuBao(fudai)
        if (isJoinFuBao) {
            fudaiList.push(fudai)
            // tool.log(`${i}添加${fudaiList.length}个福袋----${JSON.stringify(fudai)}`)
            if (fudai.delayTime < params.minOpenTime) {
                tool.log(`当前直播间福袋时间${fudai.delayTime}小于` + params.minOpenTime)
                isSuper = true
                break
            }
            if (fudaiList.length >= maxCount) {
                tool.log(`已找到${fudaiList.length}个福袋，退出采集`)
                break;
            }
        }
        //判断是否遇到马上开奖的超级福袋
        fudai = hasSuperFuDai()
        if (fudai != null) {
            tool.log("遇到马上开奖的超级福袋，退出采集")
            break
        }
        //进入下一个直播间
        nextLive(5000)
    }
    //开始参与采集的福袋
    startOpenFudai(fudai, isSuper, i)
    //重新开始采集福袋
    pickFudai()
}

/**
 * 开始参与采集的福袋
 * fudai:参与的福袋信息
 * isSuper:是否为马上开奖的超级福袋
 */
function startOpenFudai (fudai, isSuper, i) {
    tool.log("开始参与采集的福袋")
    if (!isSuper) {
        //选择最值得参与的福袋
        fudai = selectLottery()
    }
    if (fudai == null) {
        tool.log("没有福袋了，退出参与福袋")
        return
    }
    joinLottery(fudai, isSuper, i)
}


/**
 * 等待福袋开奖
 * fudai:超级福袋
 * isSuper:是否为马上开奖的超级福袋
 */
function joinLottery (fudai, isSuper, point2) {
    try {
        let ackFuDai
        if (isSuper) {
            ackFuDai = fudai
        } else {
            let backNum = 0;
            if (point2 > fudai.point) {
                backNum = point2 - fudai.point
            } else {
                backNum = fudai.point - point2
            }
            backNum = backNum + 5
            for (var i = 0; i < backNum; i++) {
                //获取当前直播间名称
                let liveName = getRoomName()
                //判断当前直播间是否为等待开奖的直播间名称
                if (liveName == fudai.name) {
                    tool.log("当前直播间为等待开奖的直播间")
                    break
                } else {
                    if (point2 > fudai.point) {
                        //返回上一个直播间
                        backLive(2500)
                    } else {
                        nextLive(2500)
                    }
                }
            }
            //等待福袋弹出来
            sleep(2000)
            //再次查询当前直播间的福袋信息，确认
            ackFuDai = getFuBaoBaseInfo()
        }
        if (ackFuDai.delayTime > params.maxOpenTime) {
            tool.log(`当前直播间福袋时间${ackFuDai.delayTime}大于` + params.maxOpenTime)
            joinNextFudai(fudai)
        } else if (ackFuDai.delayTime < 10 || ackFuDai.delayTime === NaN) {
            tool.log("当前直播间福袋时间小于10")
            joinNextFudai(fudai)
        } else if (!ackFuDai.exists) {
            tool.log("当前直播间没有福袋")
            joinNextFudai(fudai)
        } else {
            // tool.log("打开福袋:", ackFuDai)
            // tool.log(ackFuDai.openTime.toString());
            sleep(1000)
            click(ackFuDai.x, ackFuDai.y)
            sleep(1000)
            //参与成功标志
            let joinSuccess = true;
            if (ackFuDai.condition === '一键发表评论' || ackFuDai.condition === '点击参与抽奖') {
                if (!tool.clickText(ackFuDai.condition, 3000)) {
                    tool.log(`没有找到参与条件1:${ackFuDai.condition}`)
                    joinSuccess = false;
                }
            } else if (ackFuDai.condition === '去发表评论' && text("去发表评论").exists()) {
                if (!tool.clickText(ackFuDai.condition, 3000)) {
                    tool.log(`没有找到参与条件2:${ackFuDai.condition}`)
                }
                sleep(1500)
                if (!tool.clickText("发送", 1000)) {
                    joinSuccess = false;
                }
            } else if (ackFuDai.condition === '加入粉丝团' && text("加入粉丝团").exists()) {
                if (!tool.clickText(ackFuDai.condition, 3000)) {
                    tool.log(`没有找到参与条件3:${ackFuDai.condition}`)
                }
                sleep(1200)
                if (!tool.clickText(ackFuDai.condition, 3000)) {
                    tool.log(`没有找到参与条件4:${ackFuDai.condition}`)
                }
                sleep(500)
                //关闭加入成功
                press(ackFuDai.x, ackFuDai.y, 10);
                //重新参与福袋
                fudai = getFuBaoBaseInfo()
                joinLottery(fudai, true, fudai.point)
            } else if (ackFuDai.condition === '参与成功 等待开奖') {
                press(ackFuDai.x, ackFuDai.y, 10);
                joinSuccess = true;
            } else {
                tool.log("没有参与条件")
                press(ackFuDai.x, ackFuDai.y, 10);
                joinSuccess = false;
            }
            if (joinSuccess) {
                tool.log(`等待开奖:${ackFuDai.delayTime}秒`)
            } else {
                //参与下一个福袋
                joinNextFudai(fudai)
            }
            //发送评论
            sendMessage(ackFuDai.delayTime)
            //记录上次参与福袋的时间
            lastJoinTime = new Date()

            //等待开奖
            sleep(ackFuDai.delayTime * 1000)
            //获取开奖结果
            let lotteryResult = tool.handleLotteryResult()
            if (lotteryResult) {  //中奖了
                tool.log(`中奖了,等待领奖`)
                lotterySuccessResponse()
                sleep(1000 * 60 * 60 * 20)
            } else {  //没有中奖 参与下一个福袋
                tool.closeCoupon()
                joinNextFudai(fudai)
            }
        }
    } catch (e) {
        tool.log("等待开奖失败")
        joinNextFudai(fudai)
    }
}

//发送评论
function sendMessage (time) {
    threads.start(function () {
        if (time > 10) {
            let z = false;
            if (tool.clickText("聊一聊", 3000)) {
                z = true
            } else if (tool.clickDesc("说点什么", 3000)) {
                z = true
            }
            if (z) {
                sleep(1500)
                setText(params.pinglun)
                sleep(200)
                if (tool.clickTextByScreenCapture('发送')) {
                    tool.log("发送成功")
                } else {
                    tool.log("发送失败")
                }
            } else {
                tool.log("输入失败")
            }
            time = time - 25
            if (time > 20) {
                setTimeout(() => { sendMessage(time) }, 20 * 1000)
            }
        }
    });
}

//参与下一个福袋
function joinNextFudai (fudai) {
    //关闭悬浮窗
    tool.closeCoupon()
    //删除参与的福袋
    deleteFudai(fudai.name)
    let newFudai = selectLotteryByTime(params.maxOpenTime)
    if (newFudai != null) {
        joinLottery(newFudai, false, fudai.point)
    } else {
        //可参与的福袋没有了
        tool.log("可参与的福袋没有了")
    }
}

//删除未中奖和已经过期的福袋
function deleteFudai (name) {
    let newFuDaiList = []
    for (let i = 0; i < fudaiList.length; i++) {
        let targetFudai = fudaiList[i]
        let time = new Date(targetFudai.openTime).getTime() - new Date().getTime()
        if (targetFudai.name == name) {
        } else if (time < 1000 * minTime) {
        } else {
            newFuDaiList.push(targetFudai)
        }
    }
    fudaiList = newFuDaiList
}

//添加可参与的福袋
function addFudai (fudai) {
    let hasFudai = false;
    let name = fudai.name
    for (let i = 0; i < fudaiList.length; i++) {
        let targetFudai = fudaiList[i]
        if (targetFudai.name === name) {
            hasFudai = true
            break
        }
    }
    if (hasFudai) {
        fudaiList.push(fudai)
    } else {
        tool.log("已添加过该福袋")
    }
}

//判断当前福袋中是否有马上开奖的福袋
function hasSuperFuDai () {
    let fudai = null
    for (let i = 0; i < fudaiList.length; i++) {
        let targetFudai = fudaiList[i]
        //最近时间的福袋
        let time = new Date(targetFudai.openTime).getTime() - new Date().getTime()
        //tool.log(`直播间:${targetFudai.name}延迟时间:${targetFudai.delayTime}秒,价值:${targetFudai.money}元,剩余时间:${time / 1000}秒`)
        // tool.log(`直播间:${targetFudai.name},价值:${targetFudai.money},剩余:${time / 1000}秒`)
        tool.log(`价值:${targetFudai.money},剩余:${time / 1000}秒`)
        targetFudai.delayTime = time / 1000
        if (time < 1000 * params.minOpenTime && time > 1000 * minTime) {
            tool.log(`${targetFudai.name}剩余${time / 1000}秒可参与`)
            fudai = targetFudai
            break
        }
    }
    return fudai;
}

/**
 * 选择最值得参与的福袋
 * @returns 
 */
function selectLottery () {
    let fudai = hasSuperFuDai()
    if (fudaiList.length > 0) {
        if (fudai == null) {
            fudaiList.sort(function (a, b) { return b.money - a.money })
            fudai = fudaiList[0]
        }
    }
    return fudai;
}

//选择时间最近的福袋
function selectLotteryByTime (time) {
    let fudai = hasSuperFuDai()
    if (fudai == null) {
        if (fudaiList.length > 0) {
            if (time !== undefined && time !== null) {
                fudaiList.sort(function (a, b) { return a.delayTime - b.delayTime })
                if (fudaiList[0].delayTime < time) {
                    fudai = fudaiList[0]
                }
            }
        }
    }
    return fudai;
}



//抽奖成功响应
function lotterySuccessResponse () {
    //开奖了,提示声音
    for (let i = 0; i < params.winCount; i++) {
        tool.playRingtone(500, 6)
        device.vibrate(2000);
        sleep(500)
    }
}

//判断福袋是否值得参与
function hasJoinFuBao (fudai) {
    let isJoin = false;
    if (isBlackLive(fudai.name)) {   //在黑名单直播间
        tool.log("在黑名单直播间中")
        return isJoin
    }
    if (!fudai.exists) {
        tool.log("不存在福袋")
        return isJoin
    }
    if (fudai.money < params.maxMoney) {
        tool.log("福袋价值小余" + params.maxMoney)
        return isJoin
    }
    if (fudai.delayTime < minTime) {
        tool.log(`福袋延迟时间${fudai.delayTime}小于${minTime}秒`)
        return isJoin
    }
    if (fudai.delayTime > maxTime) {
        tool.log(`福袋延迟时间${fudai.delayTime}大于${maxTime}秒`)
        return isJoin
    }
    if (fudai.condition == '一键发表评论' || fudai.condition == '去发表评论' || fudai.condition == '参与抽奖' || fudai.condition == '加入粉丝团' || fudai.condition == '参与成功 等待开奖') {
        tool.log("满足福袋参与条件")
        isJoin = true
    } else {
        tool.log("不满足福袋参与条件")
        isJoin = false
    }
    return isJoin;
}

//判断是否在黑名单直播间
function isBlackLive (name) {
    let isBlack = false;
    if (name == null) {
        return isBlack
    }
    for (let i = 0; i < params.blackLiveList.length; i++) {
        if (params.blackLiveList[i] == name) {
            isBlack = true;
            break;
        }
    }
    return isBlack;
}


//查询当前直播间福袋的基础信息
function getFuBaoBaseInfo () {
    //tool.log("开始查询福袋信息")
    let fudai = {
        name: "",
        exists: false,
        x: 0,
        y: 0,
        money: 0,
        delayTime: 0,  //开奖倒计时
        openTime: null,//开奖时间
        condition: null,
        point: 0    //福袋索引
    }
    //查询直播间名称x
    fudai.name = getRoomName()
    if (fudai.name == null) {
        tool.log(`未找到直播间名称`)
        return fudai
    }
    if (isBlackLive(fudai.name)) {   //获取直播间名字失败或者在黑名单直播间
        tool.log("在黑名单直播间中")
        return fudai
    }
    //查询福袋点位
    let p = getFudai()
    if (p !== null) {
        fudai.exists = true
        fudai.x = p.x + 20
        fudai.y = p.y + 20
        // tool.log("点击福袋:")
        //打开福袋详细信息
        click(fudai.x, fudai.y)
        sleep(1200)
        //查询福袋参考价值
        fudai.money = getFuDaoValue()
        //查询福袋剩余时间
        fudai.delayTime = getFuDaoTime()
        if (fudai.delayTime > 0) {
            fudai.openTime = new Date(new Date().getTime() + fudai.delayTime * 1000)
        }
        //查询福袋参与条件
        fudai.condition = getFuDaoCondition()
        // tool.log(`关闭福袋`)
        press(fudai.x, fudai.y + 200, 20)
    } else {
        fudai.exists = false
    }
    // tool.log(`查询福袋基础信息结束:${JSON.stringify(fudai)}`)
    return fudai;
}


//查福袋位置信息
function getFudai () {
    let p = null
    for (let i = 0; i < 5; i++) {
        p = tool.findImage("zbjp.png", "fudai.png", {
            region: [0, 0, device.width / 2, device.height / 4],
            threshold: 0.5
        })
        if (p) {
            break;
        }
    }
    return p;
}


//查询当前直播间名称
function getRoomName (time) {
    if (time === undefined || time === null) {
        time = 2000
    }
    let t = null;
    if (text("搜索").exists()) {
        tool.log("不在直播间")
        return t;
    }
    let name = idContains("user_name").findOne(time);
    if (name == null) {
        tool.log("不在直播间")
        notLiveCount++
        if (notLiveCount > maxNotLiveCount) {
            notLiveCount = 0
            start()
        }
    } else {
        t = name.getText();
        //tool.log("已在直播间：", text);
        notLiveCount = 0
    }
    return t;
}
//查询开福袋的剩余时间
function getFuDaoTime () {
    let remainingSeconds = 0;
    if (textContains("后开奖").exists()) {
        try {
            var img = captureScreen("./image/fxfd.png");
            let bounds = textContains("后开奖").findOne(2000).bounds();
            let x = 465;
            let y = bounds.top
            var src = images.read("./image/fxfd.png");
            var img2 = images.clip(src, x, y, 80, 68);
            // images.save(img2, "./image/minutes.png");
            // //识别倒计时
            let minutes = paddle.ocrText(img2);
            minutes = parseInt(minutes);
            var img3 = images.clip(src, 460 + 95, y, 80, 68);
            // images.save(img3, "./image/seconds.png");
            let seconds = paddle.ocrText(img3);
            seconds = parseInt(seconds);
            //tool.log("倒计时: " + minutes + ":" + seconds);
            if (minutes !== NaN && minutes !== undefined && seconds !== NaN && seconds !== undefined) {
                remainingSeconds = minutes * 60 + seconds;
            }
            if (remainingSeconds > 900 || remainingSeconds < 0) {
                tool.log(`福袋时间错误:${remainingSeconds}，修改为默认500秒`)
                remainingSeconds = 500
            }
        } catch (e) {
            tool.log(e)
            tool.log("查询福袋剩余时间异常")
        }
    }
    if (remainingSeconds == NaN) {
        remainingSeconds = 0
    }
    // tool.log("倒计时秒: " + remainingSeconds);
    return remainingSeconds;
}



//查询福袋参与条件
function getFuDaoCondition () {
    let condition = null
    if (className("com.lynx.tasm.behavior.ui.text.FlattenUIText").text("参与成功 等待开奖").exists()) {
        condition = "参与成功 等待开奖"
    } else if (className("com.lynx.tasm.behavior.ui.text.FlattenUIText").text("一键发表评论").exists()) {
        condition = "一键发表评论"
    } else if (className("android.widget.Button").text("去发表评论").exists()) {
        condition = "去发表评论"
    } else if (text("参与抽奖").exists()) {
        condition = "参与抽奖"
    } else if (className("com.lynx.tasm.behavior.ui.text.FlattenUIText").text("加入粉丝团").exists()) {
        condition = "加入粉丝团"
    }
    return condition;
}

//查询福袋的参考价值
function getFuDaoValue () {
    var value = 0;
    if (className("com.lynx.tasm.behavior.ui.text.FlattenUIText").textStartsWith("参考价值").exists()) {
        var valueText = className("com.lynx.tasm.behavior.ui.text.FlattenUIText").textStartsWith("参考价值:").findOne(2000).text();
        value = parseInt(valueText.substr(7));
        //tool.log(`福袋参考价值:${value}`);
        return value;
    } else {
        //tool.log("没有找到参考价值");
        return 0
    }
}

//检查上一次打开福袋的时间
function checkRuning () {
    let lastTime = new Date().getTime() - new Date(lastJoinTime).getTime()
    //tool.log(`离上一次打开福袋的时间${lastTime / 1000}秒`)
    if (tool.handleLotteryResult()) {
        return
    }
    if (lastTime / 1000 / 60 > restartTime) {
        tool.log(`已有${lastTime}秒未参与福袋，重新开始`)
        lastJoinTime = new Date()
        start()
    }
}

//切换下一个直播间
function nextLive (time) {
    tool.log("切换下一个直播间")
    sleep(1000);
    let startX = random(300, 350)
    let startY = random(1500, 1600)
    let endX = random(300, 350)
    let endY = random(100, 150)
    swipe(startX, startY, endX, endY, 50)
    sleep(time)
}

//返回上一个直播间
function backLive (time) {
    tool.log("返回上一个直播间")
    let startX = random(300, 350)
    let startY = random(200, 250)
    let endX = random(300, 350)
    let endY = random(1700, 1800)
    swipe(startX, startY, endX, endY, 100)
    sleep(time)
}